package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 知识:代码格式化快捷键ctrl+alt+l
 */
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //查询出所有的分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //从所有分类中过滤出一级分类:依据所有一级分类的父id都为0
        List<CategoryEntity> firstMenu = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0).map(menu -> {
            menu.setChildren(getChildren(menu, entities));
            return menu;
        }).collect(Collectors.toList());
        //组装成父子树形结构
        return firstMenu;
    }

    @Override
    public void delMenuByIds(Long[] catIds) {
        //todo 需要判断要删除的节点是否被引用
        //实际开发中,一般采用逻辑删除,以表中的某个字段作为逻辑删除的判断依据(status),然后在配置中添加逻辑删除规则,
        //最后需要在逻辑删除字段(status)对应的实体类属性上添加@TableLogic注解
        //如果某一张表中的逻辑删除规则和配置中的规则不一样,可以通过@TableLogic(val)
        baseMapper.deleteBatchIds(Arrays.asList(catIds));


    }

    //递归查询菜单的子菜单，参数:(当前菜单,所有菜单)
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {

        List<CategoryEntity> children = all.stream().filter(
                //切记包装类对象之间比较一定要用equals()方法,否则超过128,两个integer引用的数组不一样,值就不相等了
                categoryEntity -> categoryEntity.getParentCid() .equals(root.getCatId()))
                .map((categoryEntity) -> {
                    categoryEntity.setChildren(getChildren(categoryEntity, all));
                    return categoryEntity;
                })
                .collect(Collectors.toList());
        return children;
    }

}